package com.yisu.expressway.onedollar.widget;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.yisu.expressway.R;
import com.yisu.expressway.onedollar.utils.DensityUtil;
import com.yisu.expressway.onedollar.activity.GoodsPurchaseActivity;
import com.yisu.expressway.onedollar.model.ODBannerItem;
import com.yisu.expressway.shopping_mall.YouZanWebActivity;
import com.yisu.expressway.utils.DisplayUtil;
import com.yisu.expressway.utils.StringUtil;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Created by haha on 16/2/22.
 */
public class ODSlideShowView extends FrameLayout {

    //轮播图图片数量
    private final static int IMAGE_COUNT = 5;
    //自动轮播的时间间隔
    private final static int TIME_INTERVAL = 5;
    //自动轮播启用开关
    private final static boolean isAutoPlay = true;

    //自定义轮播图的资源
    private List mDataList;
    //放轮播图片的ImageView 的list
    private List<ImageView> imageViewsList;
    //放圆点的View的list
    private List<View> dotViewsList;

    private ViewPager viewPager;
    //当前轮播页
    private int currentItem = 0;
    //定时任务
    private ScheduledExecutorService scheduledExecutorService;

    private Context context;
    private int dotMarginWidth = 0;
    private LinearLayout dotLayout;

    private Handler handler = new Handler();

    public ODSlideShowView(Context context) {
        this(context, null);
    }

    public ODSlideShowView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ODSlideShowView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
        dotMarginWidth = DisplayUtil.dip2px(context, 5);
    }

    /**
     * 开始轮播图切换
     */
    public void startPlay() {
        handler.removeCallbacksAndMessages(null);
        handler.post(new SlideShowTask());
    }

    /**
     * 停止轮播图切换
     */
    public void stopPlay() {
        handler.removeCallbacksAndMessages(null);
    }

    /**
     * 初始化相关Data
     */
    public void initData(Context ctx, List configs) {
        imageViewsList = new ArrayList<ImageView>();
        dotViewsList = new ArrayList<View>();
        this.context = ctx;
        mDataList = configs;
        if (isAutoPlay) {
            initUI(ctx);

            if (scheduledExecutorService != null) {
                scheduledExecutorService.shutdownNow();
                scheduledExecutorService = null;
            }
            //initImageLoader(ctx);
            if (mDataList != null && mDataList.size() > 1) {
                updateIndicator(0);
            }
            startPlay();

        }
    }

    /**
     * 初始化Views等UI
     */
    private void initUI(final Context context) {
        LayoutInflater.from(context).inflate(R.layout.layout_odslideshow, this, true);

        viewPager = (ViewPager) findViewById(R.id.viewPager);
        dotLayout = (LinearLayout) findViewById(R.id.dotLayout);
        dotLayout.removeAllViews();
        if (mDataList == null || mDataList.size() == 0 ){
            ImageView view = new ImageView(context);
            view.setScaleType(ScaleType.CENTER);
            view.setImageDrawable(getResources().getDrawable(R.drawable.pic_loading));
            imageViewsList.add(view);
        }else {
            for (int i = 0; i < mDataList.size(); i++) {
                Object o = mDataList.get(i);
                if (o == null) {
                    break;
                }
                ImageView view = new ImageView(context);

                if (o instanceof ODBannerItem) {
                    dotLayout.setVisibility(VISIBLE);
                    final ODBannerItem mBannerItem = (ODBannerItem) o;

                    view.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onBannerClick(mBannerItem);
                        }
                    });
                    if (!TextUtils.isEmpty(mBannerItem.imageUrl)){
                        view.setScaleType(ScaleType.FIT_XY);
                        Glide.with(getContext().getApplicationContext()).load(mBannerItem.imageUrl)
                            .placeholder(R.drawable.blank).diskCacheStrategy(DiskCacheStrategy.ALL)
                            .centerCrop().into(view);
                    }else {
                        view.setScaleType(ScaleType.CENTER);
                        view.setImageDrawable(getResources().getDrawable(R.drawable.pic_loading));
                    }

                    ImageView dotView = new ImageView(context);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

                    dotMarginWidth = dotMarginWidth == 0 ? 10 : dotMarginWidth;
                    params.leftMargin = dotMarginWidth;
                    params.rightMargin = dotMarginWidth;
                    params.gravity = Gravity.CENTER;

                    dotLayout.addView(dotView, params);
                    dotViewsList.add(dotView);
                }

                imageViewsList.add(view);

            }

        }
        // 热点个数与图片特殊相等

        viewPager.setAdapter(new MyPagerAdapter());
        viewPager.setOnPageChangeListener(new MyPageChangeListener());
        if (mDataList != null && mDataList.size() > 1) {
            updateIndicator(0);
        } else {
            dotLayout.setBackgroundResource(R.color.colorTransparent);
        }
    }

    /**
     * 销毁ImageView资源，回收内存
     */
    private void destoryBitmaps() {

        for (int i = 0; i < IMAGE_COUNT; i++) {
            ImageView imageView = imageViewsList.get(i);
            Drawable drawable = imageView.getDrawable();
            if (drawable != null) {
                //解除drawable对view的引用
                drawable.setCallback(null);
            }
        }
    }

    public void setIndicatorBackground(int resId) {
        if (dotLayout != null) {
            dotLayout.setBackgroundResource(resId);
        }
    }

    private void updateIndicator(int currentPos) {
        for (int i = 0; i < dotViewsList.size(); i++) {
            if (i == currentPos) {
                ((View) dotViewsList.get(currentPos))
                        .setBackgroundResource(R.drawable.banner_indicater_dot_select);
            } else {
                ((View) dotViewsList.get(i))
                        .setBackgroundResource(R.drawable.banner_indicater_dot_normal);
            }
        }

    }

    private void onBannerClick(ODBannerItem mBannerItem) {
        if (mBannerItem == null || StringUtil.isNullOrEmpty(mBannerItem.url)) {
            return;
        }
        if (mBannerItem.linkType.equals(ODBannerItem.LINK_TYPE_INNER)) {
            GoodsPurchaseActivity.launch(context, Long.valueOf(mBannerItem.url));
        } else if (mBannerItem.linkType.equals(ODBannerItem.LINK_TYPE_OUT)) {
            YouZanWebActivity.launch(context, mBannerItem.url, mBannerItem.title);
        }


    }

    /**
     * 填充ViewPager的页面适配器
     */
    private class MyPagerAdapter extends PagerAdapter {

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(imageViewsList.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(imageViewsList.get(position));
            return imageViewsList.get(position);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return imageViewsList.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0 == arg1;
        }
    }

    /**
     * ViewPager的监听器
     * 当ViewPager中页面的状态发生改变时调用
     */
    private class MyPageChangeListener implements OnPageChangeListener {

        boolean isAutoPlay = false;

        @Override
        public void onPageScrollStateChanged(int arg0) {
            switch (arg0) {
                case ViewPager.SCROLL_STATE_DRAGGING:// 手势滑动，空闲中
                    isAutoPlay = false;
                    if (scheduledExecutorService != null
                            && !scheduledExecutorService.isShutdown()) {
                        scheduledExecutorService.shutdownNow();
                    }
                    scheduledExecutorService = null;
                    break;
                case ViewPager.SCROLL_STATE_SETTLING:// 界面切换中
                    isAutoPlay = true;
                    break;
                case ViewPager.SCROLL_STATE_IDLE:// 滑动结束，即切换完毕或者加载完毕
                    // 当前为最后一张，此时从右向左滑，则切换到第一张
                    if (viewPager.getCurrentItem() == viewPager.getAdapter().getCount() - 1
                            && !isAutoPlay) {
                        viewPager.setCurrentItem(0);
                    }
                    // 当前为第一张，此时从左向右滑，则切换到最后一张
                    else if (viewPager.getCurrentItem() == 0 && !isAutoPlay) {
                        viewPager.setCurrentItem(viewPager.getAdapter().getCount() - 1);
                    }
                    break;
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int pos) {
            currentItem = pos;
            updateIndicator(pos);
        }

    }

    /**
     * 执行轮播图切换任务
     */
    private class SlideShowTask implements Runnable {
        @Override
        public void run() {
            if (imageViewsList != null && !imageViewsList.isEmpty()) {
                currentItem = (currentItem + 1) % imageViewsList.size();
                viewPager.setCurrentItem(currentItem);
            }
            handler.postDelayed(this, 4000);
        }
    }
}
